package com.zhugang.week06;

/**
 * @program algorithms
 * @description: inorderSuccessor
 * @author: chanzhugang
 * @create: 2022/07/18 14:38
 */
public class InorderSuccessor {


    /**
     * 面试题04.06 后继者
     *
     * @param root
     * @param p
     * @return
     */

    private boolean comming = false;
    private TreeNode successor = null;

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // 中序遍历p后面一个节点
        // 中序后继：  中序遍历，中间逻辑处理
        inorder(root, p);
        return successor;
    }

    private void inorder(TreeNode root, TreeNode p) {
        if (root == null) {
            return;
        }
        inorder(root.left, p);
        if (successor != null) {
            // 提前退出条件
            return;
        }
        if (comming == true) {
            // 通过变量判断此时是p的后一个节点
            successor = root;
            comming = false;
            return;
        }
        if (root == p) {
            comming = true;
        }
        inorder(root.right, p);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}